<template>
    <el-tree-select
        ref="treeRef"
        v-model="value"
        :data="treeData"
        check-strictly
        :render-after-expand="false"
        default-expand-all
        node-key="id"
        @node-click="handleNodeClick"
        :default-checked-keys="treeDefaultChecked"
        :disabled="disabled"
    />
</template>
<script lang="ts">
import { defineComponent,onMounted,reactive, ref, toRefs, watch} from 'vue'
import request from '/@/utils/request'

export default defineComponent({
    name: 'departmentSelectTree',
    emits: ['treeSelected'],
    props: {
        parentId: String,
        selectedId: String,
        selectedText: String,
        disabled: {
            type: Boolean,
            default: false,
        },
    },
    setup(props, context) {
        const state = reactive({
            loading: false,
            treeData: [],
            treeDefaultChecked: [],
            value: {id: '', label: ''},
        })
        const loadData = ()=>{
            state.loading = true
			request.get('/system/department/tree',{
                params:{
                    parentId: (props.parentId||'')
                }
            }).then(res => {
				state.treeData = res?.data || []
 			}).finally(()=>{
				state.loading = false
			})
        }
        const init = ()=>{
            state.treeData = [];
            state.treeDefaultChecked = [];
        }
        watch(()=>props.parentId,()=>{
            init();
            loadData();
        })
        watch(()=>props.selectedId,()=>{
            state.value = {
                id: props.selectedId || '',
                label: props.selectedText || '',
            }
        })
        onMounted(()=>{
            loadData();
            state.value = {
                id: props.selectedId || '',
                label: props.selectedText || '',
            }
        })
        const treeRef = ref();
        const handleNodeClick = (data:any)=>{
            context.emit("treeSelected", {
                id: data.id,
                label: data.label,
            });
        }
        return {
            ...toRefs(state),
            ...toRefs(props),
            handleNodeClick,
            treeRef,
        }
    }
})
</script>
